/**
 * 
 */
package climspace.client;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

import climspace.ejb.WeatherStationBean;

public class LoadSjsuClientPortal {

	private Context ctx;
	private WeatherStationBean svc;
	private String host = "localhost";

	public LoadSjsuClientPortal() {
		try {
			connectToService();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void setHost(String host) {
		this.host = host;
	}

	private Context getContext() throws Exception {
		if (ctx != null)
			return ctx;

		Properties props = new Properties();
		props.put(Context.PROVIDER_URL, "jnp://" + host + ":1099");
		props.put(Context.INITIAL_CONTEXT_FACTORY,
				"org.jnp.interfaces.NamingContextFactory");
		props.put(Context.URL_PKG_PREFIXES,
				"org.jboss.naming:org.jnp.interfaces");
		ctx = new InitialContext(props);

		return ctx;
	}

	private WeatherStationBean connectToService() throws Exception {
		if (svc != null)
			return svc;

		Context ctx = getContext();
		Object ref = ctx.lookup("WeatherStationBeanEJB/remote");
		svc = (WeatherStationBean) PortableRemoteObject.narrow(ref,
				WeatherStationBean.class);

		return svc;
	}

	public String getCurrentWeatherData(String stationId,
			String desiredOutputFormat) {
		String outputString = "";
		if (stationId == null)
			throw new RuntimeException("Missing primary_id");

		try {
			outputString = connectToService().getCurrentWeatherData(stationId,
					desiredOutputFormat);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return outputString;
	}
	public static void main(String[] args) {
		int beanCount = 10;
		System.out.println("Testing " + beanCount + " beans.");
		
		LoadSjsuClientPortal[] climSpaceClient = new LoadSjsuClientPortal[beanCount];
		
		long start = System.currentTimeMillis();
		
		for (int i=0;i<beanCount;i++) {
			climSpaceClient[i] = new LoadSjsuClientPortal();
		}
		
		long end = System.currentTimeMillis();
		System.out.println((end - start));
		System.out.println((end - start)/beanCount);
		start = end;
		
		for (int i=0;i<beanCount;i++) {
			String outputString = climSpaceClient[i].getCurrentWeatherData("KIYA",
					"kmlOutputFormat");
			//System.out.println(outputString);
		}

		end = System.currentTimeMillis();
		System.out.println((end - start));
		System.out.println((end - start)/beanCount);
	}
}
